//
//  AppDelegate.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-5-9.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "AppDelegate.h"
#import <AFNetworkActivityIndicatorManager.h>
#import "NetworkAccessManager.h"
#import "BPush.h"
#import "UIAlertView+Kirinrin.h"
#import <MMDrawerController.h>
#import "UIAlertView+Kirinrin.h"
#import "CoreData+MagicalRecord.h"

#import <TSMessage.h>
#import "MenuViewController.h"

#import <UIViewController+MMDrawerController.h>
#import "ChatViewController.h"
#import "ContactParentViewController.h"
#import "MoviePlayViewController.h"

#import "AppDelegate+EaseMob.h"


NSString *const NOTIFICATION_LOGINCHANGE = @"loginStateChange";

#define kPUSH_ACTION_IM         @"com.suplus.ibaby365.parsepush.IBABY365_PUSH_IM"
#define kPUSH_ACTION_NOTICE     @"com.suplus.ibaby365.parsepush.IBABY365_PUSH_NOTICE"
#define kPUSH_ACTION_CHECK_IN   @"com.suplus.ibaby365.parsepush.IBABY365_CHECK_IN"
#define kPUSH_ACTION_CHECK_OUT  @"com.suplus.ibaby365.parsepush.IBABY365_CHECK_OUT"
#define kPUSH_ACTION_SCORE      @"com.suplus.ibaby365.parsepush.IBABY365_CHILD_SCORE"

//两次提示的默认间隔
#define kDefaultPlaySoundInterval   3.0

@interface AppDelegate() <UIApplicationDelegate, BPushDelegate>{
   NSDate *_lastPlaySoundDate;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    //设置Tint Color
    [[UINavigationBar appearance]setBarTintColor:UIColorFromRGB(0x5cb0ee, 1)];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, /*shadow, NSShadowAttributeName,*/ [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
    
    
    /* Setup EaseMob */
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(imLoginStateChange:)
                                                 name:NOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    
    
    //init push
    [BPush setupChannel:launchOptions]; // 必须
    [BPush setDelegate:self]; // 必须。参数对象必须实现onMethod: response:方法，本示例中为self
    
    
    if (launchOptions) {
        NSDictionary*userInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        if(userInfo)
        {
            //启动参数的处理
            [self didReiveceRemoteNotificatison:userInfo];
        }
    }
    
    /*
    NSDictionary *pushInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    NSLog(@"action = %@", [pushInfo objectForKey:@"action"]);
    //TODO:自动登录及根据参数打开指定的页
    if ([pushInfo objectForKey:@"action"]) {
        //baidu push
        NSLog(@"action");
        if ([pushInfo[@"action"]isEqualToString:kPUSH_ACTION_NOTICE]) {
            //
            NSLog(@"notice type = %d", [pushInfo[@"type"]intValue]);
            if ([pushInfo[@"action"]isEqualToString:kPUSH_ACTION_NOTICE]) {
                if ([pushInfo[@"type"]intValue] == 2) {
                    self.startUpPage = menuNotice;
                }else if ([pushInfo[@"type"]intValue] == 6){
                    self.startUpPage = menuRest;
                }
            }
        }else if ([pushInfo[@"action"]isEqualToString:kPUSH_ACTION_CHECK_IN] ||[pushInfo[@"action"]isEqualToString:kPUSH_ACTION_CHECK_OUT]){
            self.startUpPage = menuCheckOn;
        }else if ([pushInfo[@"action"]isEqualToString:kPUSH_ACTION_SCORE]){
            self.startUpPage = menuScore;
        }
    }else{
        self.startUpPage = menuSNS;
    }
    */

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    [[EaseMob sharedInstance] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    application.applicationIconBadgeNumber =0;
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [[EaseMob sharedInstance] applicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    //    NSLog(@"");
    
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}

#pragma mark - save and restore application state auto sign in
-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder{
    return  NO;
}
-(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder{
    return NO;
}
-(void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder{
    NSLog(@"encode");
    [coder encodeObject:self.accessKey forKey:@"accessKey"];
    [coder encodeObject:self.userId forKey:@"userId"];
    [coder encodeInteger:self.userType forKey:@"userType"];
    [coder encodeObject:self.user forKey:@"user"];
}
-(void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder{
    NSLog(@"decode %@", coder);
    self.accessKey = [coder decodeObjectForKey:@"accessKey"];
    self.userId = [coder decodeObjectForKey:@"userId"];
    self.userType = [coder decodeIntegerForKey:@"userType"];
    self.user = [coder decodeObjectForKey:@"user"];
}

- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder{
    NSLog(@"path %@", identifierComponents);
    if ([[identifierComponents lastObject]isEqualToString:@"Drawer"]) {
        
        NSLog(@"path %@", identifierComponents);
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        UIViewController *centerController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"NavMainView"];
        
        UIViewController *leftController = nil;
        
        leftController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"Menu"];
        
        UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:centerController];
        
        MMDrawerController *drawerController = [[MMDrawerController alloc]initWithCenterViewController:navigationController leftDrawerViewController:leftController];
        drawerController.restorationIdentifier = @"Drawer";
        [drawerController setMaximumLeftDrawerWidth:249.0];
        [drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
        [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
        
        return drawerController;
    }
    return nil;
}

#pragma mark - APNS
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    NSLog(@"deviceToken %@", deviceToken);
    
    [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    
    [BPush registerDeviceToken:deviceToken]; // 必须
    
    [BPush bindChannel]; // 必须。可以在其它时机调用，只有在该方法返回（通过onMethod:response:回调）绑定成功时，app才能接收到Push消息。一个app绑定成功至少一次即可（如果access token变更请重新绑定）。
}
// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    [[EaseMob sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
    NSLog(@"error -- %@",error);
}



- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    application.applicationIconBadgeNumber += 1;
    
    //区分是环信的调用还是百度的调用，后分别处理
    NSString *pushMessage = nil;
    if ([userInfo objectForKey:@"action"]) {
        //baidu push
        if ([userInfo[@"action"]isEqualToString:kPUSH_ACTION_NOTICE]) {
            if ([userInfo[@"type"]intValue] == 2) {
                pushMessage = [NSString stringWithFormat:@"%@: %@",@"通知", userInfo[@"aps"][@"alert"]];
            }else if ([userInfo[@"type"]intValue] == 6){
                pushMessage = [NSString stringWithFormat:@"%@: %@",@"请假", userInfo[@"aps"][@"alert"]];
            }
        } else if ([userInfo[@"action"]isEqualToString:kPUSH_ACTION_CHECK_IN]){
            pushMessage = [NSString stringWithFormat:@"%@: %@",@"入园", userInfo[@"aps"][@"alert"]];
            
        }else if ([userInfo[@"action"]isEqualToString:kPUSH_ACTION_CHECK_OUT]){
            pushMessage = [NSString stringWithFormat:@"%@: %@",@"离园", userInfo[@"aps"][@"alert"]];
        }else if ([userInfo[@"action"]isEqualToString:kPUSH_ACTION_SCORE]){
            pushMessage = [NSString stringWithFormat:@"%@: %@",@"在园表现", userInfo[@"aps"][@"alert"]];
        }
        else{
            pushMessage = [NSString stringWithFormat:@"%@: %@",@"通告", userInfo[@"aps"][@"alert"]];
        }
        
    }else{
        //im push
        pushMessage = [NSString stringWithFormat:@"%@: %@",@"消息", userInfo[@"aps"][@"alert"]];
    }
    
    
    [TSMessage showNotificationWithTitle:@"iBaby365消息" subtitle:pushMessage type:TSMessageNotificationTypeMessage];
    
    [BPush handleNotification:userInfo];
   
}


- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    //if loginIn jump to chart history View
    if (self.menuController) {
        id centerViewController = self.menuController.mm_drawerController.centerViewController;
        if ([centerViewController isKindOfClass:[ChatViewController class]] || [centerViewController isKindOfClass:[ContactParentViewController class]]) {
            //do nothing
        }else{
            [self.menuController toChatAction:nil];
        }
        
    }
}




#pragma EaseMod
// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message{
    
#if !TARGET_IPHONE_SIMULATOR
    [self playSoundAndVibration];
    
    BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
    if (!isAppActivity) {
        [self showNotificationWithMessage:message];
    }else{
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = @"[图片]";
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = @"[位置]";
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = @"[音频]";
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = @"[视频]";
            }
                break;
            default:
                break;
        }
        [TSMessage showNotificationWithTitle:@"聊天消息" subtitle:messageStr type:TSMessageNotificationTypeMessage];
    }
#endif
}

- (void)playSoundAndVibration{
    
    //如果距离上次响铃和震动时间太短, 则跳过响铃
    NSLog(@"%@, %@", [NSDate date], _lastPlaySoundDate);
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:_lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        return;
    }
    //保存最后一次响铃时间
    _lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EaseMob sharedInstance].deviceManager asyncPlayNewMessageSound];
    // 收到消息时，震动
    [[EaseMob sharedInstance].deviceManager asyncPlayVibration];
}

- (void)showNotificationWithMessage:(EMMessage *)message{
    id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
    NSString *messageStr = nil;
    switch (messageBody.messageBodyType) {
        case eMessageBodyType_Text:
        {
            messageStr = ((EMTextMessageBody *)messageBody).text;
        }
            break;
        case eMessageBodyType_Image:
        {
            messageStr = @"[图片]";
        }
            break;
        case eMessageBodyType_Location:
        {
            messageStr = @"[位置]";
        }
            break;
        case eMessageBodyType_Voice:
        {
            messageStr = @"[音频]";
        }
            break;
        case eMessageBodyType_Video:{
            messageStr = @"[视频]";
        }
            break;
        default:
            break;
    }
    
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    //    NSString *title = message.from;
    /*
     if (message.isGroup) {
     NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
     for (EMGroup *group in groupArray) {
     if ([group.groupId isEqualToString:message.conversation.chatter]) {
     title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
     break;
     }
     }
     }
     */
    notification.alertBody = [NSString stringWithFormat:@"%@", messageStr];
//    notification.alertAction = kPUSH_ACTION_IM;
    notification.timeZone = [NSTimeZone defaultTimeZone];
    
    [notification setUserInfo:@{@"senderId": message.from, @"content":messageStr, @"type":@(messageBody.messageBodyType)}];
    
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber += 1;
}



#pragma mark - APNS
// 打印收到的apns信息
-(void)didReiveceRemoteNotificatison:(NSDictionary *)userInfo{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo
                                                        options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *str =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"推送内容"
                                                    message:str
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                          otherButtonTitles:nil];
    [alert show];
    
}
@end
